import socket
import select
import time

connections = [];

#Initialization of a server socket
def initialize(port):
	test = socket.socket(socket.AF_INET, socket.SOCK_STREAM);
	test.connect(("msn.com",80));
	myIP = test.getsockname()[0];
	test.close();
	
	s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	s.bind((myIP, port))
	s.listen(5)
	return s;

def track_socket(e):
	global connections;
	s = socket.socket(socket.AF_INET, socket.SOCK_STREAM);
	socket.setdefaulttimeout(1);
	try: s.connect((e['ip'],e['port']))
	except socket.error, err:
		print "error: %s"%err
		return False;
	e['socket'] = s
	connections.append(e);
	print "connected to %s"%e['ip']
	return e

def closed_socket(s):
	global connections;
	for index, a in enumerate(connections):
		if a['socket'] == s:
			connections.pop(index);
			return True;
	return False;
			
def main_loop(timeoutCallback,initializeCallback,port=6886):
	global connections;
	server = initialize(port);
	while 1:
		waitlist = [a['socket'] for a in connections]
		waitlist.append(server)
		(ready,_,_) = select.select(waitlist,[],[],5)
		if server in ready:
			(nc,addr) = server.accept()
			initializeCallback(nc,addr);
		for a in connections:
			if a['socket'] in ready:
				a['callback'](a)
		if len(ready) == 0:
			if timeoutCallback():
				break;
